import Icon from '@/components/Icon'
import { changeActive, getUserChannel } from '@/store/action/home'
import { RootState } from '@/types/store'
import { useInitialState } from '@/utils/hooks'
import { Popup, Tabs } from 'antd-mobile'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router'
import ArticleList from './ArticleList'
import Channels from './Channels'

import styles from './index.module.scss'

const Home = () => {
  const [visible, setVisible] = useState(false)
  const channels = useInitialState(getUserChannel, 'home').userChannel
  const hide = () => {
    setVisible(false)
  }
  const active = useSelector((state: RootState) => state.home.active)
  const dispatch = useDispatch()
  const history = useHistory()

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      {channels.length > 0 && (
        <Tabs
          className="tabs"
          activeLineMode="fixed"
          activeKey={active + ''}
          onChange={(value) => dispatch(changeActive(+value))}
        >
          {channels.map((item) => (
            <Tabs.Tab title={item.name} key={item.id}>
              <ArticleList channelId={item.id}></ArticleList>
            </Tabs.Tab>
          ))}
        </Tabs>
      )}

      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup visible={visible} position="left">
        <Channels hide={hide}></Channels>
      </Popup>
    </div>
  )
}

export default Home
